import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:library_base/constant/constant.dart';
import 'package:library_base/ext/string_ext.dart';
import 'package:library_base/ext/double_ext.dart';
import 'package:library_base/ext/theme_data_ext.dart';
import 'package:library_base/global/multi_language.dart';
import 'package:library_base/net/apis.dart';
import 'package:library_base/network/http_config.dart';
import 'package:library_base/network/http_util.dart';
import 'package:library_base/network/transform/fb_parse_transform.dart';
import 'package:library_base/res/decoration.dart';
import 'package:library_base/res/dividing_line.dart';
import 'package:library_base/res/edge.dart';
import 'package:library_base/res/gaps.dart';
import 'package:library_base/res/styles.dart';
import 'package:library_base/res/widget_generator.dart';
import 'package:library_base/utils/num_util.dart';
import 'package:library_base/utils/sp_util.dart';
import 'package:library_base/utils/theme_util.dart';
import 'package:library_base/utils/toast_util.dart';
import 'package:library_base/utils/widget_generate_util.dart';
import 'package:library_base/widget/button/gradient_button.dart';
import 'package:library_base/widget/image/local_image.dart';
import 'package:library_base/ext/bool_ext.dart';
import 'package:library_base/utils/get_util.dart';

class CreateWmsGoodsDialog extends StatefulWidget {
  const CreateWmsGoodsDialog({
    Key? key,
  }) : super(key: key);

  @override
  State<CreateWmsGoodsDialog> createState() =>
      _CreateWmsGoodsDialogState();
}

class _CreateWmsGoodsDialogState extends State<CreateWmsGoodsDialog> {

  var loginEnabled = false;

  late String goodsCode;

  late double stockOutWeigh;

  late String goodsBarCode;

  late String batchNo;

  late double stockOutCount;

  double mainWeigh = 0.0;

  late double subWeigh;

  late double skinWeight;

  late String stockOutId;

  late String goodsName;

  String? locationId;

  late bool singleEntry;

  late Function() updatePosition;

  TextEditingController goodsCountController = TextEditingController();
  FocusNode goodsCountFocusNode = FocusNode();

  TextEditingController goodsWeightController = TextEditingController();
  FocusNode goodsWeightFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    updatePosition = Get.arguments['updatePosition'];

    singleEntry = Get.arguments['singleEntry'];
    goodsCode = Get.arguments['goodsCode'];
    locationId = Get.arguments['locationId'];
    batchNo = Get.arguments['batchNo'];
    stockOutId = Get.arguments['stockOutId'];

    if(singleEntry){
      mainWeigh = Get.arguments['mainWeigh'];
      subWeigh = Get.arguments['subWeigh'];
      goodsBarCode = Get.arguments['goodsBarCode'];
      skinWeight = Get.arguments['skinWeight'];

      goodsCountController.text = mainWeigh > 0 ? (SPUtil.isJin?(NumUtil.add(mainWeigh, skinWeight))*2:NumUtil.add(mainWeigh, skinWeight)).toString() : '';
      goodsWeightController.text = subWeigh > 0.0 ? (SPUtil.isJin?subWeigh*2:subWeigh).toString() : '';

    }else{
      stockOutCount = Get.arguments['stockOutCount'];
      stockOutWeigh = Get.arguments['stockOutWeigh'];
      goodsName = Get.arguments['goodsName'];
      goodsCountController.text = stockOutCount > 0 ? stockOutCount.toString() : '';
      goodsWeightController.text = stockOutWeigh > 0.0 ? stockOutWeigh.numAsUnitStr() : '';
    }

    loginEnabled = isCanSubmit();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: WillPopScope(
          onWillPop: () {
            GetHelper.back();
            return Future.value(false);
          },
          child: GestureDetector(
            onTap: () => Get.back(),
            child: Container(
              padding: const EdgeInsets.only(bottom: 50),
              width: double.infinity,
              color: Colors.transparent,
              alignment: Alignment.center,
              height: double.infinity,
              child: Row(
                children: [
                  SizedBox(width: 0.06.sw),
                  Expanded(
                    child: Container(
                      decoration: rs8,
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(
                            height: 95.w,
                            width: double.infinity,
                            child: Stack(
                              children: [
                                Container(
                                    alignment: Alignment.center,
                                    child: Text(MultiLanguage.locationEntry.tr,
                                        style: normalTextColor34)),
                                Positioned(
                                  top: 10.w,
                                  right: 0,
                                  child: GestureDetector(
                                    onTap: () => Get.back(),
                                    child: Padding(
                                        padding: edgeAll24,
                                        child: LocalImage('common_close',
                                            package: Constant.packLib(),
                                            width: 26.w,
                                            height: 26.w)),
                                  ),
                                )
                              ],
                            ),
                          ),
                          line1,
                          Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              gapH24,
                              Row(children: [
                                Expanded(
                                    flex: titleWeight(),
                                    child: Text(
                                      singleEntry?MultiLanguage.barcode.tr:MultiLanguage.productName.tr,
                                      style: normalTextColor28,
                                      textAlign: TextAlign.end,
                                    )),
                                gapW24,
                                Expanded(
                                    flex: contentWeight(),
                                    child: Text(
                                      singleEntry?goodsBarCode:goodsName,
                                      style: normalTextColor28,
                                    )),
                                gapW24,
                              ]),
                              Visibility(
                                  visible: singleEntry,
                                  child: gapH18),
                              Visibility(
                                visible: singleEntry,
                                child: Row(children: [
                                  Expanded(
                                      flex: titleWeight(),
                                      child: Text(
                                        "${MultiLanguage.tareDeduction.tr}\n(${SPUtil.isJin.unitStrZh()})",
                                        style: normalTextColor28,
                                        textAlign: TextAlign.end,
                                      )),
                                  gapW24,
                                  Expanded(
                                      flex: contentWeight(),
                                      child: Text(
                                        SPUtil.isJin?(SPUtil.skinWeight*2).toString():SPUtil.skinWeight.toString(),
                                        style: normalTextColor28,
                                      )),
                                  gapW24,
                                ]),
                              ),
                              Visibility(
                                  visible: singleEntry,
                                  child: gapH18),
                              Visibility(
                                visible: singleEntry,
                                child: Row(children: [
                                  Expanded(
                                      flex: titleWeight(),
                                      child: Text(
                                        "${MultiLanguage.peelMainWeight.tr}\n(${SPUtil.isJin.unitStrZh()})",
                                        style: normalTextColor28,
                                        textAlign: TextAlign.end,
                                      )),
                                  gapW24,
                                  Expanded(
                                      flex: contentWeight(),
                                      child: Text(
                                        mainWeigh.toString(),
                                        style: normalTextColor28,
                                      )),
                                  gapW24,
                                ]),
                              ),
                              gapH18,
                              _buildInputItem(
                                title: title2(),
                                hint: title2Hint(),
                                controller: goodsCountController,
                                focusNode: goodsCountFocusNode,
                                onChanged: _countChange,
                              ),
                              gapH18,
                              _buildInputItem(
                                title: title3(),
                                hint: title3Hint(),
                                controller: goodsWeightController,
                                focusNode: goodsWeightFocusNode,
                                onChanged: _weightChange,
                              ),
                              gapH24,
                            ],
                          ),
                          line1,
                          GradientButton(
                            ThemeUtil.getTheme(),
                            width: double.infinity,
                            height: 77.r,
                            margin: edgeV36H24 as EdgeInsets,
                            colors: ThemeUtil.getTheme().buttonRight1BgColor(),
                            text: MultiLanguage.determine.tr,
                            onPressed: loginEnabled ? determine : null,
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(width: 0.06.sw),
                ],
              ),
            ),
          )),
    );
  }

  buildItem(
      {GestureTapCallback? onTap,
        required String title,
        required String hint,
        String? content}) {
    return Row(children: [
      Expanded(
          flex: titleWeight(),
          child:
          Text(title, style: normalTextColor28, textAlign: TextAlign.end)),
      gapW24,
      Expanded(
          flex: contentWeight(),
          child: GestureDetector(
            onTap: onTap,
            child: Container(
                padding: edgeAll24,
                decoration: BoxDecoration(
                    borderRadius: const BorderRadius.all(Radius.circular(30.0)),
                    border: Border.all(
                        color: ThemeUtil.getTheme().secondaryTextColor(),
                        width: 0.7)),
                child: Row(children: [
                  Expanded(
                      child: Text(
                          content == null || content.isEmpty ? hint : content,
                          style: content == null || content.isEmpty
                              ? TextStyles.textSecondary28
                              : normalTextColor28)),
                  LocalImage('common_grey_rightward_arrow',
                      package: Constant.packLib(), width: 20.w, height: 20.w),
                ])),
          )),
      gapW24,
    ]);
  }

  _buildInputItem({
    required String title,
    required String hint,
    TextEditingController? controller,
    FocusNode? focusNode,
    ValueChanged<String>? onChanged,
  }) {
    return Row(children: [
      Expanded(
          flex: titleWeight(),
          child:
          Text(title, style: normalTextColor28, textAlign: TextAlign.end)),
      gapW24,
      Expanded(
          flex: contentWeight(),
          child: buildInput(
            padding: edgeAll24,
            hintText: hint,
            controller: controller,
            focusNode: focusNode,
            textAlign: TextAlign.start,
            margin: const EdgeInsets.all(0),
            onChanged: onChanged,
          )),
      gapW24,
    ]);
  }

  determine() {
    var map = {};
    map['stockOutId'] = stockOutId;
    map['goodsCode'] = goodsCode;
    map['batchNo'] = batchNo;
    map['locationId'] = locationId;
    if(singleEntry){
      double mainWeightWithSkin = double.parse(goodsCountController.text);
      mainWeightWithSkin = SPUtil.isJin?NumUtil.divide(mainWeightWithSkin, 2):mainWeightWithSkin;
      double subWeight = 0.0;

      map['goodsBarCode'] = goodsBarCode;
      map['mainWeigh'] = NumUtil.subtract(mainWeightWithSkin, SPUtil.skinWeight);

      if(goodsWeightController.text.isNotEmpty){
        if(NumUtil.isNumber(goodsWeightController.text)){
          subWeight = double.parse(goodsWeightController.text);
        }
        subWeight = SPUtil.isJin?NumUtil.divide(subWeight, 2):subWeight;
        map['subWeigh'] = subWeight;
      }else{
        map['subWeigh'] = 0.0;
      }
      map['skinMainWeight'] = mainWeightWithSkin;
      map['skinWeight'] = SPUtil.skinWeight;
    }else{
      map['stockOutCount'] = double.parse(goodsCountController.text);
      map['stockOutWeigh'] = goodsWeightController.text.strAsUnitNum();
    }
    FBHttpUtil.post<Map>(context, Apis.WEIGHING_RECORD,
        params: map,
        requestLoading: GenerateWidgetUtil.loadingDialog(context),
        transformer: FBParseTransform((result) => result)).then((value) {
      if (value['code'] == HttpConfig.successCode) {
        updatePosition();
        GetHelper.back();
      } else {
        ToastUtil.error(value['msg']);
      }
    }).catchError((err) {
      ToastUtil.error(err.toString());
    });
  }

  ///判断是否自家的服务器标准的json格式,默认是有code和data即可
  bool isStandardJson(Map<dynamic, dynamic> data) {
    return data.containsKey('code') &&
        data.containsKey('data') &&
        data.containsKey('msg');
  }

  ///计算采购金额和重量
  void _countChange(String value) {
    if(singleEntry){
      if(NumUtil.isNumber(goodsCountController.text)){
        double mainWeightWithSkin = double.parse(goodsCountController.text);
        mainWeigh = NumUtil.subtract(mainWeightWithSkin, SPUtil.skinWeight);
      }else{
        mainWeigh = 0.0;
      }
    }
    loginEnabled = isCanSubmit();
    setState(() {});
  }

  ///计算采购金额和重量
  void _weightChange(String value) {
    loginEnabled = isCanSubmit();
    setState(() {});
  }

  bool isCanSubmit() {
    if (!NumUtil.isNumber(goodsCountController.text)) {
      return false;
    } else {
      if (double.parse(goodsCountController.text) <= 0.0) {
        return false;
      }
    }

    if(singleEntry){
      if(goodsWeightController.text.isNotEmpty){
        if (!NumUtil.isNumber(goodsWeightController.text)) {
          return false;
        } else {
          if (double.parse(goodsWeightController.text) < 0.0) {
            return false;
          }
        }
      }
    }else{
        if (!NumUtil.isNumber(goodsWeightController.text)) {
          return false;
        } else {
          if (double.parse(goodsWeightController.text) < 0.0) {
            return false;
          }
        }
    }
    return true;
  }

  int titleWeight() =>singleEntry? 4:2;

  int contentWeight() =>singleEntry? 6:5;

  String title1() =>singleEntry? MultiLanguage.barcode.tr:MultiLanguage.productName.tr;

  String title2() =>singleEntry? "${MultiLanguage.weightMainWithSkinWeight.tr}\n(${SPUtil.isJin.unitStrZh()})":MultiLanguage.commodityQuantity.tr;

  String title3() =>singleEntry? "${MultiLanguage.complementaryGoodsWeight.tr}\n(${SPUtil.isJin.unitStrZh()})":"${MultiLanguage.weightGoods.tr}\n${SPUtil.isJin.unitStrZhWithBracket()}";

  String title2Hint() =>singleEntry? MultiLanguage.pleaseInputWeight.tr:MultiLanguage.pleaseInputQuantity.tr;

  String title3Hint() =>"${MultiLanguage.pleaseInputWeight.tr}${SPUtil.isJin.unitStrZhWithBracket()}";

}
